package com.ruoyi.web.controller.webgroup;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.webgroup.*;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.webgroupservcie.ClockCountService;
import com.ruoyi.system.webgroupservcie.ClockService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.sql.Time;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

/**
 * 打卡的controller层
 */
@Api("签到签退")
@RestController
@RequestMapping("/web/clock")
public class ClockController extends BaseController {

    @Autowired
    private ClockService clockService;

    @Autowired
    private ClockCountService clockCountService;
    @Autowired
    private ISysUserService userService;

    @ApiOperation("查询所有记录")
    //@RequestMapping("/clockAll")
    @RequestMapping("/list")
    public TableDataInfo selectClockAll(Clock clock){
        startPage();
//        SysUser sysUser = userService.selectUserById(clock.getUserId().longValue());
//        clock.setSysUser(sysUser);
        List<Clock> clocks = clockService.selectClockAll(clock);
        return getDataTable(clocks);
    }
    /**
     * 导出打卡记录列表
     */
    //@PreAuthorize("@ss.hasPermi('system:clock:export')")
    @Log(title = "导出表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Clock clock)
    {
        List<Clock> list = clockService.selectClockAll(clock);
        ExcelUtil<Clock> util = new ExcelUtil<Clock>(Clock.class);
        util.exportExcel(response, list, "打卡数据");
    }



    /**根据该表主键clockId查询*/
    @GetMapping("/{clockId}")
    public AjaxResult getClock(@PathVariable("clockId") Integer clockId){
        Clock clock = clockService.getClock(clockId);
        return AjaxResult.success(clock);
    }

    /**根据该表主键删除*/
    @DeleteMapping("/{clockIds}")
    public AjaxResult deleteClock(@PathVariable("clockIds") Integer[] clockIds){
        //clockService.deleteClock(clockId);
        //return AjaxResult.success();
        return toAjax(clockService.deleteClock(clockIds));
    }

    /**根据表单修改修改*/
    @PutMapping
    public AjaxResult putClock(@RequestBody Clock clock){
        return toAjax(clockService.putClock(clock));
    }

    /**增加数据*/
/*
    @PostMapping
    public AjaxResult postClock(@RequestBody Clock clock){
        if (clock != null){
            clockService.postClock(clock);
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }
*/

    /**根据当前日期查签到签退状态*/
    @GetMapping("/getClockState/{userId}/{clockDatetime}")
    public AjaxResult getClockState(@PathVariable Integer userId,@PathVariable Date clockDatetime){
        Integer clockState = clockService.getClockState(userId,clockDatetime);
        //查到数据就是已当前数据另一种状态，没有查到数据就返回0
        if (clockState == null){
                return AjaxResult.success(0);
        }else if(clockState == 0){
            return AjaxResult.success(1);
        }else{
            return AjaxResult.success(0);
        }
    }



    /**进行签到签退，增加数据*/
    @PostMapping
    @Transactional
    public AjaxResult increaseClock(@RequestBody Clock clock){
        try{
            //先插入签到签退的数据
            clockService.postClock(clock);

            //签退就结算当前的时间段，然后插入数据
            if (clock.getClockState() == 1){
                //获取当前用户id
                Integer userId = clock.getUserId();
                //查询当前日期和当前用户下第二高clock_id的日期(签到日期)
                Date clockDatetime = clockService.getClockDatetime(userId);
                //获取当前签退日期
                Date clockDatetime1 = clock.getClockDatetime();
                //查询俩签退减去签到日期
                Time timeDiff = clockService.getTimeDiff(clockDatetime1, clockDatetime);
                //记录的时间段的实体类
                ClockCount clockCount = new ClockCount(null, timeDiff, clockDatetime1, userId);
                //插入时间段的数据
                clockCountService.postClockCountById(clockCount);
                String s = clockDatetime1 + "";
                //处理前端过来的日期
                //SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd");
                String dateString = sim.format(clockDatetime1);

                //插入日榜的数据
                //先查询当前的日期有没有值
                /**签退结束就查有没有记录，没有记录就插入时间和当前的time
                 * -- 如果有就查询当前的日前的，然后累计加
                 * -- 查的时候带上当前日期和用户id
                 */
                Integer dailyListId = clockService.selectDailyList(dateString,userId);
                if (dailyListId == null){
                    DailyList dailyList = new DailyList(null, timeDiff, clockDatetime1, userId);
                    clockService.insertIntoDailyList(dailyList);
                }else{
                    clockService.insertIntoDailyListById(dailyListId,timeDiff);
                }
                //插入周榜的数据
                //先查询当前的日期有没有值
               /** -- 签退结束就查有没有记录，没有记录就插入时间和当前的time
                        -- 如果有就累加，首先要保证是这周内的
                        -- 查的时候，就查上周的记录，就会查到一个时间，就是第一次签到签退时间*/
                Integer weeklyListId = clockService.selectWeeklyList(userId);
                if(weeklyListId == null){
                    //为null就插入当前的数据
                    WeeklyList weeklyList = new WeeklyList(null, timeDiff+"", clockDatetime1, userId);
                    clockService.insertIntoWeeklyListById(weeklyList);
                }else{
                    //不为null1就累加进去
                    clockService.updateWeeklyList(weeklyListId,timeDiff);
                }


                /**总榜*/
                //这里考虑优化问题（比如用户注册的时候就是0）
                Integer generalListId = clockService.selectGeneralList(userId);
                if(generalListId == null){
                    GeneralList generalList = new GeneralList(null, timeDiff+"", userId);
                    clockService.insertIntoGeneralList(generalList);
                }else{
                    clockService.updateGeneralList(generalListId,timeDiff);
                }
            }
            return AjaxResult.success("打卡成功!");
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error();
        }
    }

}
